package com.boot.app.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.boot.app.system.domain.SystemMessage;
import com.boot.app.system.dto.MessageDto;
import com.boot.app.system.mapper.SystemMessageMapper;
import com.boot.app.system.service.ISystemMessageService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SystemMessageServiceImpl extends ServiceImpl<SystemMessageMapper, SystemMessage> implements ISystemMessageService {

    @Autowired
    private SystemMessageMapper systemMessageMapper;

    private List<MessageDto> toDtoTree(List<SystemMessage> list, long parentId){
        List<MessageDto> res = new ArrayList<>();
        list.forEach(ele -> {
            if(ele.getParentId() == parentId){
                List<MessageDto> children = toDtoTree(list, ele.getId());
                MessageDto dto = new MessageDto();
                BeanUtils.copyProperties(ele, dto);
                dto.setChildren(children);
                res.add(dto);
            }
        });
        return res;
    }

    @Override
    public List<MessageDto> fetchTree() {
        LambdaQueryWrapper<SystemMessage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemMessage::getStatus, 1);
        List<SystemMessage> list = systemMessageMapper.selectList(queryWrapper);
        return toDtoTree(list, 0);
    }

    @Override
    public List<MessageDto> fetchTreeNotLeaf() {
        LambdaQueryWrapper<SystemMessage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemMessage::getIsLeaf, false);
        queryWrapper.eq(SystemMessage::getStatus, 1);
        List<SystemMessage> list = systemMessageMapper.selectList(queryWrapper);
        return toDtoTree(list, 0);
    }
}
